//
//  ShopSetViewController.m
//  Business
//
//  Created by CccDaxIN on 16/9/27.
//  Copyright © 2016年 macox. All rights reserved.
//

#import "ShopSetViewController.h"
#import "shopAddImageView.h"
#import "SGGenerateQRCodeVC.h"
#import "SGScanningQRCodeVC.h"
#import <AVFoundation/AVFoundation.h>
@interface ShopSetViewController ()<UIScrollViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
{
    NSOperationQueue *operationQueue;
    NSString * strOne;
    NSString * judge;
    UIButton *shopImageButton;//添加按钮
    UIButton *deleteImageButton;//删除按钮
    NSInteger imageCount;
    NSData *dataPostTwo;
}
@property (strong, nonatomic) IBOutlet UIScrollView *shopSetScrollView;
@property (strong, nonatomic) NSString *recordState;//纪录imagebutton
@property (assign, nonatomic) NSInteger recordPosition;//纪录位置
@property (nonatomic,strong)NSMutableArray *data_array;
@end

@implementation ShopSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = SHOPNAME;
    [NNSingleton sharedSingleton].setUpORcommodity = @"店铺设置";
    
    [self showsData];//  展示数据
    [self createSubViewORAdjustment];
    
    /*
     *返回
     */
    UIImage *shopSetBackImage = [UIImage imageNamed:@"左箭头"];
    shopSetBackImage = [shopSetBackImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:shopSetBackImage style:UIBarButtonItemStylePlain target:self action:@selector(shopSetBackAction)];
    
    // Do any additional setup after loading the view from its nib.
}
#pragma mark --返回
- (void)shopSetBackAction{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    /*
     Reduce the size of the text view so that it's not obscured by the keyboard.
     Animate the resize so that it's in sync with the appearance of the keyboard.
     */
    NSDictionary *userInfo = [notification userInfo];
    // Get the origin of the keyboard when it's displayed.
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect tableViewFrame = self.view.bounds;
    tableViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
    
    // Get the duration of the animation.
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    
    _bottomScrollView.frame = CGRectMake(0,0, kScrernWidth,keyboardTop);
    [UIView commitAnimations];
}
- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary* userInfo = [notification userInfo];
    /*
     Restore the size of the text view (fill self's view).
     Animate the resize so that it's in sync with the disappearance of the keyboard.
     */
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    _bottomScrollView.frame = CGRectMake(0,0, kScrernWidth,kScrernHeight);
    [UIView commitAnimations];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark -- 展示已存在的店铺信息
- (void)showsData{
    
    //显示店铺图片
    if ( [NNSingleton sharedSingleton].shopsData[@"Logo"] == [NSNull alloc]) {
        judge = @"logo";
        _shopsLogoImage.image = [UIImage imageNamed:@"首页头像占位图"];
        
    }else{
        judge = @"data";
        NSURL *url = [NNSingleton sharedSingleton].shopsData[@"Logo"];
        NSString *imageStr = [NSString stringWithFormat:@"%@%@",ReleaseORDebug,url];
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageStr]];
        strOne = [data base64EncodedStringWithOptions:kNilOptions];
        _shopsLogoImage.image = [UIImage imageWithData:data];
    }
    
    if ([NNSingleton sharedSingleton].shopsData[@"ShopName"] == [NSNull alloc] ) {
        self.stopsName.text = @"";
    }else{
        self.stopsName.text = [NNSingleton sharedSingleton].shopsData[@"ShopName"];
    }
    if ([NNSingleton sharedSingleton].shopsData[@"YingYeRQ"] == [NSNull alloc] ) {
        self.businessHoursTextField.text = @"";
    }else{
        self.businessHoursTextField.text = [NNSingleton sharedSingleton].shopsData[@"YingYeRQ"];
    }
 }
#pragma ---设置
- (void)createSubViewORAdjustment{
    _businessHoursTextField.delegate = self;

    /*
     设置scrollview
     */
    self.shopSetScrollView.showsVerticalScrollIndicator = FALSE;
    self.shopSetScrollView.contentSize = CGSizeMake(kScrernWidth*2+10,0);
    self.shopSetScrollView.delegate = self;
    
    //展示店铺实景图(最多5张)
    shopAddImageView *shopImageView = [[shopAddImageView alloc]initWithFrame:CGRectMake(0, 5, kScrernWidth*2, 100)];
    [self.shopSetScrollView addSubview:shopImageView];
    
    /*
     *设置logo圆角
     */
    [_shopsLogoImage.layer setMasksToBounds:YES];
    [_shopsLogoImage.layer setBorderWidth:1];//设置边界的宽度
    _shopsLogoImage.layer.cornerRadius = 25;
    _shopsLogoImage.layer.borderColor = [UIColor colorWithRed:0.70 green:0.70 blue:0.70 alpha:1.00].CGColor;
}
#pragma mark -- 设置店铺logo
- (IBAction)setShopsLogoButton {
    NSLog(@"更换店铺头像");
    [self selectPictureUploadMode];
}

-(void)verifyIdentifier:(UIImage *)image {
    NSData *dataPostOne = [self resetSizeOfImageData:image maxSize:1024];
    strOne = [dataPostOne base64EncodedStringWithOptions:kNilOptions];
    _shopsLogoImage.image = [UIImage imageWithData:dataPostOne];
    judge = @"data";
}
- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize{
    //先调整分辨率
    CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);
    CGFloat tempHeight = newSize.height / 1024;
    CGFloat tempWidth = newSize.width / 1024;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
    } else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
    }
    UIGraphicsBeginImageContext(newSize);
    [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //调整大小
    NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);
    NSUInteger sizeOrigin = [imageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    if (sizeOriginKB > maxSize) {
        NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.3);
        return finallImageData;
    }
    return imageData;
}
#pragma mark -- 选择图片上传方式
- (void)selectPictureUploadMode{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择照片" message:@"从相册选取照片或拍照发送" preferredStyle:UIAlertControllerStyleActionSheet];
    
    // 1、 获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        [alert addAction:[UIAlertAction actionWithTitle:@"相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
            imagePickController.delegate = self;
            imagePickController.allowsEditing = YES;
            imagePickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickController animated:YES completion:^{
            }];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if(authStatus == AVAuthorizationStatusAuthorized){
                NSLog(@"允许状态");
                UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
                imagePickController.delegate = self;
                imagePickController.allowsEditing = YES;
                imagePickController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:imagePickController animated:YES completion:^{
                }];
            }else if (authStatus == AVAuthorizationStatusDenied){
                NSLog(@"不允许状态，可以弹出一个alertview提示用户在隐私设置中开启权限");
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"未获得授权使用摄像头" message:@"请在iOS“设置”-“隐私”-“相机”中打开" preferredStyle:UIAlertControllerStyleAlert];
                
                [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [alert dismissViewControllerAnimated:YES completion:nil];
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            }
            else if (authStatus == AVAuthorizationStatusNotDetermined)
            {
                NSLog(@"系统还未知是否访问，第一次开启相机时");
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    //*******************先回主线程
                    if (granted) {
                        //第一次用户接受
                    }else{
                        //用户拒绝
                    }
                }];
            }
        }]];
    } else {
        [alert addAction:[UIAlertAction actionWithTitle:@"相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
            imagePickController.delegate = self;
            imagePickController.allowsEditing = YES;
            imagePickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickController animated:YES completion:^{
            }];
        }]];
    }
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alert animated:YES completion:nil];

}

#pragma mark - UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self verifyIdentifier:image];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName {
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 1.f);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}
- (IBAction)holdShopInformation:(UIButton *)sender {
    NSLog(@"保存");
    if ([judge isEqualToString:@"logo"]) {
        [SVProgressHUD showErrorWithStatus:@"请上传logo图片" ];
        return;
    }
    if (!self.businessHoursTextField.text.length) {
        [SVProgressHUD showErrorWithStatus:@"请输入营业时间" ];
        return;
    }else if ([self.businessHoursTextField.text isEqualToString:@"0"]){
        [SVProgressHUD showErrorWithStatus:@"请输入营业时间" ];
        return;
    }
       [self storeSettingsPreservationDataDataRequest];
}

#pragma mark -- 保存数据
- (void)storeSettingsPreservationDataDataRequest{
    NSLog(@"终于做了这个决定 %@,  %@ %@",GETPHONE,GETUUID,GETTOKEN);
    [SVProgressHUD showWithStatus:@"正在上传"];
    [GDJHttpTool post:StoreSettingPreservation params:@{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN,@"YingYeRQ":self.businessHoursTextField.text,@"ShopLogo":strOne,@"ShopPic":[NNSingleton sharedSingleton].imageArray} success:^(id responseObj) {
        //查看错误码
        NSInteger err = [[responseObj valueForKey:@"Err"]integerValue];
        NSLog(@"问题 %ld",(long)err);
        if (err == 0) {
            [SVProgressHUD dismiss];
            NSLog(@"成功");
            [self.navigationController popViewControllerAnimated:YES];
        }else if(err == 132){
            [SVProgressHUD showErrorWithStatus:@"请至少上传一张图片" ];
            return;
        }else if(err == 999){
            [SVProgressHUD showErrorWithStatus:responseObj[@"ErrMsg" ]];
            return;
        }else{
            NSLog(@"%@",responseObj[@"ErrMsg"]);
            [SVProgressHUD showErrorWithStatus:responseObj[@"ErrMsg"]];
            return;
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
